package com.smartstate.EMS.config.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * <p>Title: MessageProducer</p >
 * <p>Description: MQ生产者</p >
 */
@Slf4j
@Component
public class MessageProducer {
  /**
   * 主机IP
   */
  public String HOST ="127.0.0.1";
  /**
   * 端口
   */
  public Integer PORT = 5672;
  /**
   * 用户名
   */
  public String USERNAME = "admin";
  /**
   * 密码
   */
  public String PASSWORD = "admin";

  //创建工厂类
  private static ConnectionFactory factory = new ConnectionFactory();

  //创建连接
  private static Connection connection = null;
  //创建Channel
  private static Channel channel = null;

  private MessageProducer()  {
    //设置参数
    factory.setHost(HOST);
    factory.setPort(PORT);
    factory.setUsername(USERNAME);
    factory.setPassword(PASSWORD);
    factory.setVirtualHost("/");
  }

  private MessageProducer( String HOST,Integer PORT,String USERNAME,String PASSWORD) {
    //设置参数
    factory.setHost(HOST);
    factory.setPort(PORT);
    factory.setUsername(USERNAME);
    factory.setPassword(PASSWORD);
    factory.setVirtualHost("/");
  }

  public static void publish(String startJson) throws IOException, TimeoutException {
    String exchange = "test";
    String queue = "test.data.upstream";
    String routingKey = "test.data.upstream";
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.basicPublish(exchange, queue, MessageProperties.PERSISTENT_TEXT_PLAIN, (startJson).getBytes());
    channel.queueBind(queue,exchange,routingKey);
    channel.addConfirmListener(new ConfirmListener() {
      @Override
      public void handleAck(long deliveryTag, boolean multiple) throws IOException {
        log.error("发送失败记录：" + deliveryTag);
      }

      @Override
      public void handleNack(long deliveryTag, boolean multiple) throws IOException {
        log.info(String.format("发送成功消息，标识：%d，多个消息：%b", deliveryTag, multiple));
      }
    });

    channel.close();
    connection.close();
  }
}
